'use strict';

const oauthServer = require('oauth2-server');

const models = require('../models');

class TokenModel {
    getAccessToken(bearerToken) {
        return models.OAuthTokens.findOne({ accessToken: bearerToken });
    }

    getClient(clientId, clientSecret) {
        return models.OAuthClients.findOne({ clientId: clientId, clientSecret: clientSecret });
    }

    getRefreshToken(refreshToken) {
        return OAuthTokensModel.findOne({ refreshToken: refreshToken });
    }

    getUser(username, password) {
        return OAuthUsersModel.findOne({ username: username, password: password });
    }

    saveToken(token, client, user) {
        let accessToken = new OAuthTokensModel({
            accessToken: token.accessToken,
            accessTokenExpiresOn: token.accessTokenExpiresOn,
            clientId: client.id,
            refreshToken: token.refreshToken,
            refreshTokenExpiresOn: token.refreshTokenExpiresOn,
            userId: user.id
        });
        return accessToken.save();
    }
}

module.exports =  () => {
    const oauth = new oauthServer({ debug: true, model: new TokenModel() });
    return (req, res, next) => {
        let routeCfg = req.routeCfg;
        if(!routeCfg.anonymous) {
            oauth.authorise()(req, res, next)
        }else{
            next();
        }
    }
};